<template>
  <div class="message-notification">
    <!-- 通知方式配置 -->
    <el-card class="notification-card">
      <template #header>
        <div class="card-header">
          <span>通知方式配置</span>
          <el-button type="primary" @click="handleSaveChannels" :loading="saving">
            保存配置
          </el-button>
        </div>
      </template>
      <el-form
        ref="channelFormRef"
        :model="channelForm"
        label-width="120px"
      >
        <el-form-item label="站内消息">
          <el-switch v-model="channelForm.inApp.enabled" />
          <div class="channel-tips" v-if="channelForm.inApp.enabled">
            <el-checkbox v-model="channelForm.inApp.sound">提示音</el-checkbox>
            <el-checkbox v-model="channelForm.inApp.desktop">桌面通知</el-checkbox>
            <el-checkbox v-model="channelForm.inApp.badge">未读角标</el-checkbox>
          </div>
        </el-form-item>
        <el-form-item label="邮件通知">
          <el-switch v-model="channelForm.email.enabled" />
          <div class="channel-tips" v-if="channelForm.email.enabled">
            <el-input
              v-model="channelForm.email.address"
              placeholder="接收邮箱地址"
              style="width: 300px"
            />
            <el-button type="primary" link @click="testEmailChannel">
              发送测试邮件
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="短信通知">
          <el-switch v-model="channelForm.sms.enabled" />
          <div class="channel-tips" v-if="channelForm.sms.enabled">
            <el-input
              v-model="channelForm.sms.phone"
              placeholder="接收手机号"
              style="width: 200px"
            />
            <el-button type="primary" link @click="testSmsChannel">
              发送测试短信
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="企业微信">
          <el-switch v-model="channelForm.wecom.enabled" />
          <div class="channel-tips" v-if="channelForm.wecom.enabled">
            <el-input
              v-model="channelForm.wecom.corpId"
              placeholder="企业ID"
              style="width: 200px"
            />
            <el-input
              v-model="channelForm.wecom.agentId"
              placeholder="应用ID"
              style="width: 200px"
            />
            <el-button type="primary" link @click="testWecomChannel">
              发送测试消息
            </el-button>
          </div>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 通知规则管理 -->
    <el-card class="notification-card">
      <template #header>
        <div class="card-header">
          <div class="header-left">
            <span>通知规则管理</span>
            <el-input
              v-model="searchQuery"
              placeholder="搜索规则名称"
              clearable
              @clear="handleSearch"
              @keyup.enter="handleSearch"
              style="width: 200px; margin-left: 16px"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>
          <div class="header-right">
            <el-button-group>
              <el-button
                type="primary"
                :disabled="!selectedRules.length"
                @click="handleBatchEnable"
              >
                <el-icon><Check /></el-icon>批量启用
              </el-button>
              <el-button
                type="warning"
                :disabled="!selectedRules.length"
                @click="handleBatchDisable"
              >
                <el-icon><Close /></el-icon>批量禁用
              </el-button>
              <el-button
                type="danger"
                :disabled="!selectedRules.length"
                @click="handleBatchDelete"
              >
                <el-icon><Delete /></el-icon>批量删除
              </el-button>
            </el-button-group>
            <el-dropdown @command="handleExport" style="margin-left: 16px">
              <el-button type="primary">
                <el-icon><Download /></el-icon>导出
                <el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="exportRules">导出规则配置</el-dropdown-item>
                  <el-dropdown-item command="exportRecords">导出通知记录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button type="primary" @click="handleCreateRule" style="margin-left: 16px">
              <el-icon><Plus /></el-icon>新建规则
            </el-button>
          </div>
        </div>
      </template>

      <el-table
        :data="ruleList"
        border
        v-loading="loading"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="name" label="规则名称" min-width="150" />
        <el-table-column prop="type" label="消息类型" width="120">
          <template #default="scope">
            <el-tag :type="getMessageTypeTag(scope.row.type)">
              {{ getMessageTypeLabel(scope.row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="channels" label="通知方式" min-width="200">
          <template #default="scope">
            <el-tag
              v-for="channel in scope.row.channels"
              :key="channel"
              class="channel-tag"
              :type="getChannelTagType(channel)"
            >
              {{ getChannelLabel(channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="触发条件" min-width="200">
          <template #default="scope">
            <div class="condition-text">{{ formatCondition(scope.row.condition) }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              link
              @click="handleEditRule(scope.row)"
            >编辑</el-button>
            <el-button
              type="primary"
              link
              @click="handleViewRecords(scope.row)"
            >记录</el-button>
            <el-button
              type="danger"
              link
              @click="handleDeleteRule(scope.row)"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pageNum"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 规则表单对话框 -->
    <el-dialog
      v-model="ruleDialogVisible"
      :title="dialogType === 'create' ? '新建规则' : '编辑规则'"
      width="700px"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="规则名称" prop="name">
          <el-input v-model="ruleForm.name" placeholder="请输入规则名称" />
        </el-form-item>
        <el-form-item label="消息类型" prop="type">
          <el-select v-model="ruleForm.type" placeholder="请选择消息类型">
            <el-option
              v-for="type in messageTypes"
              :key="type.value"
              :label="type.label"
              :value="type.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="通知方式" prop="channels">
          <el-checkbox-group v-model="ruleForm.channels">
            <el-checkbox label="inApp">站内消息</el-checkbox>
            <el-checkbox label="email">邮件通知</el-checkbox>
            <el-checkbox label="sms">短信通知</el-checkbox>
            <el-checkbox label="wecom">企业微信</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="触发条件" prop="condition">
          <div class="condition-editor">
            <div class="condition-group">
              <el-select v-model="ruleForm.condition.type" placeholder="条件类型">
                <el-option label="消息状态" value="status" />
                <el-option label="消息类型" value="type" />
                <el-option label="消息标签" value="tag" />
                <el-option label="时间范围" value="time" />
              </el-select>
              <el-select
                v-if="ruleForm.condition.type === 'status'"
                v-model="ruleForm.condition.value"
                placeholder="选择状态"
              >
                <el-option label="未读" value="unread" />
                <el-option label="已读" value="read" />
                <el-option label="已处理" value="processed" />
                <el-option label="已关闭" value="closed" />
              </el-select>
              <el-select
                v-if="ruleForm.condition.type === 'type'"
                v-model="ruleForm.condition.value"
                placeholder="选择类型"
              >
                <el-option
                  v-for="type in messageTypes"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                />
              </el-select>
              <el-select
                v-if="ruleForm.condition.type === 'tag'"
                v-model="ruleForm.condition.value"
                placeholder="选择标签"
                multiple
              >
                <el-option
                  v-for="tag in messageTags"
                  :key="tag.id"
                  :label="tag.name"
                  :value="tag.id"
                />
              </el-select>
              <el-time-picker
                v-if="ruleForm.condition.type === 'time'"
                v-model="ruleForm.condition.value"
                is-range
                range-separator="至"
                start-placeholder="开始时间"
                end-placeholder="结束时间"
                format="HH:mm"
              />
            </div>
            <el-button type="primary" link @click="addCondition">
              <el-icon><Plus /></el-icon>添加条件
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="通知内容" prop="content">
          <el-input
            v-model="ruleForm.content"
            type="textarea"
            :rows="4"
            placeholder="请输入通知内容，支持变量：{{message.title}}、{{message.content}}等"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="ruleForm.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="ruleDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitRuleForm" :loading="submitting">
          确定
        </el-button>
      </template>
    </el-dialog>

    <!-- 通知记录对话框 -->
    <el-dialog
      v-model="recordsDialogVisible"
      title="通知记录"
      width="800px"
    >
      <div class="records-header">
        <el-date-picker
          v-model="recordDateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleRecordDateChange"
        />
      </div>
      <el-table
        :data="recordList"
        border
        v-loading="recordsLoading"
        style="width: 100%"
      >
        <el-table-column prop="createTime" label="通知时间" width="180" />
        <el-table-column prop="channel" label="通知方式" width="120">
          <template #default="scope">
            <el-tag :type="getChannelTagType(scope.row.channel)">
              {{ getChannelLabel(scope.row.channel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="content" label="通知内容" min-width="200" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getRecordStatusTag(scope.row.status)">
              {{ getRecordStatusLabel(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="error" label="错误信息" min-width="200" />
      </el-table>
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="recordPageNum"
          v-model:page-size="recordPageSize"
          :total="recordTotal"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleRecordSizeChange"
          @current-change="handleRecordCurrentChange"
        />
      </div>
    </el-dialog>

    <!-- 导出配置对话框 -->
    <el-dialog
      v-model="exportDialogVisible"
      :title="exportType === 'rules' ? '导出规则配置' : '导出通知记录'"
      width="500px"
    >
      <el-form
        ref="exportFormRef"
        :model="exportForm"
        label-width="100px"
      >
        <el-form-item label="导出格式">
          <el-radio-group v-model="exportForm.format">
            <el-radio label="excel">Excel</el-radio>
            <el-radio label="csv">CSV</el-radio>
          </el-radio-group>
        </el-form-item>
        <template v-if="exportType === 'records'">
          <el-form-item label="日期范围">
            <el-date-picker
              v-model="exportForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="导出字段">
            <el-checkbox-group v-model="exportForm.fields">
              <el-checkbox label="createTime">通知时间</el-checkbox>
              <el-checkbox label="channel">通知方式</el-checkbox>
              <el-checkbox label="content">通知内容</el-checkbox>
              <el-checkbox label="status">状态</el-checkbox>
              <el-checkbox label="error">错误信息</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
        <template v-else>
          <el-form-item label="导出字段">
            <el-checkbox-group v-model="exportForm.fields">
              <el-checkbox label="name">规则名称</el-checkbox>
              <el-checkbox label="type">消息类型</el-checkbox>
              <el-checkbox label="channels">通知方式</el-checkbox>
              <el-checkbox label="condition">触发条件</el-checkbox>
              <el-checkbox label="content">通知内容</el-checkbox>
              <el-checkbox label="status">状态</el-checkbox>
              <el-checkbox label="remark">备注</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="exportDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmExport" :loading="exporting">
          确定导出
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Search,
  Plus,
  Delete,
  Download,
  ArrowDown,
  Check,
  Close
} from '@element-plus/icons-vue'
import {
  getMessageSettings,
  updateMessageSettings,
  getReminderList,
  createReminder,
  updateReminder,
  deleteReminder,
  updateReminderStatus,
  getReminderRecords,
  getReminderStatistics,
  getReminderChannels,
  testReminderChannel,
  getMessageTypes,
  getAllMessageTags,
  exportReminderRules,
  exportReminderRecords,
  batchUpdateReminderStatus,
  batchDeleteReminders
} from '@/api/message'

// 数据加载状态
const loading = ref(false)
const saving = ref(false)
const submitting = ref(false)
const recordsLoading = ref(false)

// 分页数据
const pageNum = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 记录分页数据
const recordPageNum = ref(1)
const recordPageSize = ref(10)
const recordTotal = ref(0)
const recordDateRange = ref([])

// 搜索条件
const searchQuery = ref('')

// 列表数据
const ruleList = ref([])
const recordList = ref([])
const messageTypes = ref([])
const messageTags = ref([])

// 对话框显示状态
const ruleDialogVisible = ref(false)
const recordsDialogVisible = ref(false)
const dialogType = ref('create')

// 表单引用
const channelFormRef = ref(null)
const ruleFormRef = ref(null)

// 通知方式配置表单
const channelForm = reactive({
  inApp: {
    enabled: false,
    sound: false,
    desktop: false,
    badge: false
  },
  email: {
    enabled: false,
    address: ''
  },
  sms: {
    enabled: false,
    phone: ''
  },
  wecom: {
    enabled: false,
    corpId: '',
    agentId: ''
  }
})

// 规则表单
const ruleForm = reactive({
  id: '',
  name: '',
  type: '',
  channels: [],
  condition: {
    type: '',
    value: null
  },
  content: '',
  remark: ''
})

// 表单验证规则
const rules = {
  name: [{ required: true, message: '请输入规则名称', trigger: 'blur' }],
  type: [{ required: true, message: '请选择消息类型', trigger: 'change' }],
  channels: [{ required: true, message: '请选择通知方式', trigger: 'change' }],
  condition: [{ required: true, message: '请设置触发条件', trigger: 'change' }],
  content: [{ required: true, message: '请输入通知内容', trigger: 'blur' }]
}

// 选中的规则
const selectedRules = ref([])

// 导出相关
const exportDialogVisible = ref(false)
const exportType = ref('rules')
const exporting = ref(false)
const exportForm = reactive({
  format: 'excel',
  dateRange: [],
  fields: []
})

// 初始化数据
onMounted(async () => {
  await Promise.all([
    fetchChannels(),
    fetchRuleList(),
    fetchMessageTypes(),
    fetchMessageTags()
  ])
})

// 获取通知方式配置
const fetchChannels = async () => {
  try {
    const res = await getMessageSettings()
    Object.assign(channelForm, res.data.channels)
  } catch (error) {
    console.error('获取通知方式配置失败:', error)
    ElMessage.error('获取通知方式配置失败')
  }
}

// 获取规则列表
const fetchRuleList = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      query: searchQuery.value
    }
    const res = await getReminderList(params)
    ruleList.value = res.data.list
    total.value = res.data.total
  } catch (error) {
    console.error('获取规则列表失败:', error)
    ElMessage.error('获取规则列表失败')
  } finally {
    loading.value = false
  }
}

// 获取消息类型
const fetchMessageTypes = async () => {
  try {
    const res = await getMessageTypes()
    messageTypes.value = res.data
  } catch (error) {
    console.error('获取消息类型失败:', error)
    ElMessage.error('获取消息类型失败')
  }
}

// 获取消息标签
const fetchMessageTags = async () => {
  try {
    const res = await getAllMessageTags()
    messageTags.value = res.data
  } catch (error) {
    console.error('获取消息标签失败:', error)
    ElMessage.error('获取消息标签失败')
  }
}

// 保存通知方式配置
const handleSaveChannels = async () => {
  try {
    await updateMessageSettings({ channels: channelForm })
    ElMessage.success('保存成功')
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  }
}

// 测试通知渠道
const testEmailChannel = async () => {
  try {
    await testReminderChannel({
      channel: 'email',
      address: channelForm.email.address
    })
    ElMessage.success('测试邮件发送成功')
  } catch (error) {
    console.error('发送测试邮件失败:', error)
    ElMessage.error('发送测试邮件失败')
  }
}

const testSmsChannel = async () => {
  try {
    await testReminderChannel({
      channel: 'sms',
      phone: channelForm.sms.phone
    })
    ElMessage.success('测试短信发送成功')
  } catch (error) {
    console.error('发送测试短信失败:', error)
    ElMessage.error('发送测试短信失败')
  }
}

const testWecomChannel = async () => {
  try {
    await testReminderChannel({
      channel: 'wecom',
      corpId: channelForm.wecom.corpId,
      agentId: channelForm.wecom.agentId
    })
    ElMessage.success('测试企业微信消息发送成功')
  } catch (error) {
    console.error('发送测试企业微信消息失败:', error)
    ElMessage.error('发送测试企业微信消息失败')
  }
}

// 搜索处理
const handleSearch = () => {
  pageNum.value = 1
  fetchRuleList()
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  fetchRuleList()
}

const handleCurrentChange = (val) => {
  pageNum.value = val
  fetchRuleList()
}

// 新建规则
const handleCreateRule = () => {
  dialogType.value = 'create'
  Object.assign(ruleForm, {
    id: '',
    name: '',
    type: '',
    channels: [],
    condition: {
      type: '',
      value: null
    },
    content: '',
    remark: ''
  })
  ruleDialogVisible.value = true
}

// 编辑规则
const handleEditRule = (row) => {
  dialogType.value = 'edit'
  Object.assign(ruleForm, row)
  ruleDialogVisible.value = true
}

// 查看记录
const handleViewRecords = (row) => {
  recordsDialogVisible.value = true
  fetchRecordList(row.id)
}

// 删除规则
const handleDeleteRule = (row) => {
  ElMessageBox.confirm('确定要删除该规则吗？', '提示', {
    type: 'warning'
  }).then(async () => {
    try {
      await deleteReminder(row.id)
      ElMessage.success('删除成功')
      fetchRuleList()
    } catch (error) {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  })
}

// 状态变更
const handleStatusChange = async (row) => {
  try {
    await updateReminderStatus(row.id, row.status)
    ElMessage.success('状态更新成功')
  } catch (error) {
    console.error('状态更新失败:', error)
    ElMessage.error('状态更新失败')
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加条件
const addCondition = () => {
  ruleForm.condition.push({
    type: '',
    value: null
  })
}

// 获取记录列表
const fetchRecordList = async (ruleId) => {
  recordsLoading.value = true
  try {
    const params = {
      pageNum: recordPageNum.value,
      pageSize: recordPageSize.value,
      ruleId,
      startDate: recordDateRange.value?.[0],
      endDate: recordDateRange.value?.[1]
    }
    const res = await getReminderRecords(params)
    recordList.value = res.data.list
    recordTotal.value = res.data.total
  } catch (error) {
    console.error('获取记录列表失败:', error)
    ElMessage.error('获取记录列表失败')
  } finally {
    recordsLoading.value = false
  }
}

// 记录日期变化
const handleRecordDateChange = () => {
  recordPageNum.value = 1
  fetchRecordList()
}

// 记录分页处理
const handleRecordSizeChange = (val) => {
  recordPageSize.value = val
  fetchRecordList()
}

const handleRecordCurrentChange = (val) => {
  recordPageNum.value = val
  fetchRecordList()
}

// 提交规则表单
const submitRuleForm = async () => {
  if (!ruleFormRef.value) return
  
  try {
    await ruleFormRef.value.validate()
    submitting.value = true
    
    if (dialogType.value === 'create') {
      await createReminder(ruleForm)
      ElMessage.success('创建成功')
    } else {
      await updateReminder(ruleForm)
      ElMessage.success('更新成功')
    }
    
    ruleDialogVisible.value = false
    fetchRuleList()
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error(error.message || '提交失败')
  } finally {
    submitting.value = false
  }
}

// 格式化条件
const formatCondition = (condition) => {
  if (!condition) return ''
  
  const typeMap = {
    status: '消息状态',
    type: '消息类型',
    tag: '消息标签',
    time: '时间范围'
  }
  
  const valueMap = {
    unread: '未读',
    read: '已读',
    processed: '已处理',
    closed: '已关闭'
  }
  
  let text = `${typeMap[condition.type] || condition.type}：`
  
  if (condition.type === 'status') {
    text += valueMap[condition.value] || condition.value
  } else if (condition.type === 'type') {
    const type = messageTypes.value.find(t => t.value === condition.value)
    text += type ? type.label : condition.value
  } else if (condition.type === 'tag') {
    const tags = condition.value.map(id => {
      const tag = messageTags.value.find(t => t.id === id)
      return tag ? tag.name : id
    })
    text += tags.join('、')
  } else if (condition.type === 'time') {
    text += `${condition.value[0]} 至 ${condition.value[1]}`
  }
  
  return text
}

// 工具函数
const getMessageTypeTag = (type) => {
  const typeMap = {
    system: 'info',
    notification: 'success',
    warning: 'warning',
    error: 'danger'
  }
  return typeMap[type] || ''
}

const getMessageTypeLabel = (type) => {
  const typeItem = messageTypes.value.find(t => t.value === type)
  return typeItem ? typeItem.label : type
}

const getChannelTagType = (channel) => {
  const typeMap = {
    inApp: '',
    email: 'success',
    sms: 'warning',
    wecom: 'info'
  }
  return typeMap[channel] || ''
}

const getChannelLabel = (channel) => {
  const labelMap = {
    inApp: '站内消息',
    email: '邮件通知',
    sms: '短信通知',
    wecom: '企业微信'
  }
  return labelMap[channel] || channel
}

const getRecordStatusTag = (status) => {
  const typeMap = {
    success: 'success',
    failed: 'danger',
    pending: 'warning'
  }
  return typeMap[status] || ''
}

const getRecordStatusLabel = (status) => {
  const labelMap = {
    success: '成功',
    failed: '失败',
    pending: '处理中'
  }
  return labelMap[status] || status
}

// 处理表格选择
const handleSelectionChange = (selection) => {
  selectedRules.value = selection
}

// 批量启用
const handleBatchEnable = async () => {
  if (!selectedRules.value.length) return
  
  try {
    await batchUpdateReminderStatus(
      selectedRules.value.map(rule => rule.id),
      1
    )
    ElMessage.success('批量启用成功')
    fetchRuleList()
  } catch (error) {
    console.error('批量启用失败:', error)
    ElMessage.error('批量启用失败')
  }
}

// 批量禁用
const handleBatchDisable = async () => {
  if (!selectedRules.value.length) return
  
  try {
    await batchUpdateReminderStatus(
      selectedRules.value.map(rule => rule.id),
      0
    )
    ElMessage.success('批量禁用成功')
    fetchRuleList()
  } catch (error) {
    console.error('批量禁用失败:', error)
    ElMessage.error('批量禁用失败')
  }
}

// 批量删除
const handleBatchDelete = () => {
  if (!selectedRules.value.length) return
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedRules.value.length} 条规则吗？`,
    '提示',
    {
      type: 'warning'
    }
  ).then(async () => {
    try {
      await batchDeleteReminders(selectedRules.value.map(rule => rule.id))
      ElMessage.success('批量删除成功')
      fetchRuleList()
    } catch (error) {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  })
}

// 处理导出
const handleExport = (type) => {
  exportType.value = type
  exportForm.fields = type === 'rules' 
    ? ['name', 'type', 'channels', 'condition', 'content', 'status']
    : ['createTime', 'channel', 'content', 'status', 'error']
  exportDialogVisible.value = true
}

// 确认导出
const confirmExport = async () => {
  if (!exportForm.fields.length) {
    ElMessage.warning('请选择导出字段')
    return
  }
  
  if (exportType.value === 'records' && !exportForm.dateRange?.length) {
    ElMessage.warning('请选择日期范围')
    return
  }
  
  exporting.value = true
  try {
    const params = {
      format: exportForm.format,
      fields: exportForm.fields,
      ...(exportType.value === 'records' && {
        startDate: exportForm.dateRange[0],
        endDate: exportForm.dateRange[1]
      })
    }
    
    const res = await (exportType.value === 'rules'
      ? exportReminderRules(params)
      : exportReminderRecords(params))
    
    // 下载文件
    const blob = new Blob([res.data], {
      type: exportForm.format === 'excel'
        ? 'application/vnd.ms-excel'
        : 'text/csv'
    })
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = `${exportType.value === 'rules' ? '通知规则' : '通知记录'}_${new Date().toLocaleDateString()}.${exportForm.format}`
    link.click()
    window.URL.revokeObjectURL(url)
    
    ElMessage.success('导出成功')
    exportDialogVisible.value = false
  } catch (error) {
    console.error('导出失败:', error)
    ElMessage.error('导出失败')
  } finally {
    exporting.value = false
  }
}
</script>

<style lang="scss" scoped>
.message-notification {
  padding: 20px;

  .notification-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-left {
        display: flex;
        align-items: center;
        gap: 16px;
      }

      .header-right {
        display: flex;
        align-items: center;
        gap: 16px;
      }
    }

    .channel-tips {
      margin-top: 8px;
      color: #909399;
      font-size: 14px;
    }

    .channel-tag {
      margin-right: 8px;
      margin-bottom: 4px;
    }

    .condition-text {
      color: #606266;
      font-size: 14px;
    }

    .condition-editor {
      .condition-group {
        display: flex;
        gap: 8px;
        margin-bottom: 8px;
      }
    }

    .records-header {
      margin-bottom: 16px;
    }

    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style> 